package com.example.physicalexaminationsystem.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.example.physicalexaminationsystem.constans.RedisKeys;
import com.example.physicalexaminationsystem.dto.ResponseDto;
import com.example.physicalexaminationsystem.mapper.*;
import com.example.physicalexaminationsystem.model.NormalExamineEntity;
import com.example.physicalexaminationsystem.model.ProjectEntity;
import com.example.physicalexaminationsystem.model.SpecialExamineEntity;
import com.example.physicalexaminationsystem.vo.ExamineReportVO;
import com.example.physicalexaminationsystem.vo.SpecialExamineVO;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author shiwenzhuo
 * 
 * @description
 */
@Component
public class ExamineService {
    @Resource
    private ExaminerDao examinerDao;
    @Resource
    private NormalExamineDao normalExamineDao;
    @Resource
    private SpecialExamineDao specialExamineDao;
    @Resource
    private MealDao mealDao;
    @Resource
    private Jedis jedis;
    @Resource
    private ProjectDao projectDao;

    //通过体检人姓名获取体检报告
    public ExamineReportVO getExamineReportByName(String name) {
        ExamineReportVO examineReportVO = new ExamineReportVO();
        Long mealId = examinerDao.selectByMap(MapUtil.of("name", name)).get(0).getMealId();
        String idListKey = String.format(RedisKeys.MEAL_PROJECT_ID_LIST, mealId);
        Set<String> projectIds = jedis.zrange(idListKey, 0, -1);
        List<SpecialExamineVO> specialExamineVOS = new ArrayList<>();
        for (String projectId : projectIds) {
            SpecialExamineVO specialExamineVO = new SpecialExamineVO();
            ProjectEntity projectEntity = projectDao.selectById(Long.valueOf(projectId));
            Map<String, Object> param = new HashMap<>();
            param.put("name", name);
            param.put("projectId", projectId);
            List<SpecialExamineEntity> specialExamineEntities = specialExamineDao.selectByMap(param);
            SpecialExamineEntity specialExamineEntity = CollUtil.isEmpty(specialExamineEntities) ? null : specialExamineEntities.get(0);
            Double maxLevel = projectEntity.getMaxLevel();
            Double minLevel = projectEntity.getMinLevel();
            specialExamineVO.setMaxLevel(maxLevel);
            specialExamineVO.setMinLevel(minLevel);
            specialExamineVO.setProjectName(projectEntity.getName());
            specialExamineVO.setError(specialExamineEntity == null ? "" : specialExamineEntity.getError());
            specialExamineVO.setResult(specialExamineEntity == null ? 0 : specialExamineEntity.getResult());
            specialExamineVO.setSuggest(specialExamineEntity == null ? "" : specialExamineEntity.getSuggest());
            specialExamineVOS.add(specialExamineVO);
        }
        examineReportVO.setName(name);
        List<NormalExamineEntity> normalExamineEntities = normalExamineDao.selectByMap(MapUtil.of("name", name));
        NormalExamineEntity normalExamineEntity = CollUtil.isEmpty(normalExamineEntities) ? null : normalExamineEntities.get(0);
        examineReportVO.setBmi(normalExamineEntity == null ? 0 : normalExamineEntity.getBmi());
        examineReportVO.setDiastolicPressure(normalExamineEntity == null ? 0 : normalExamineEntity.getDiastolicPressure());
        examineReportVO.setHeight(normalExamineEntity == null ? 0 : normalExamineEntity.getHeight());
        examineReportVO.setIdealWeight(normalExamineEntity == null ? 0 : normalExamineEntity.getIdealWeight());
        examineReportVO.setSystolicPressure(normalExamineEntity == null ? 0 : normalExamineEntity.getSystolicPressure());
        examineReportVO.setWeight(normalExamineEntity == null ? 0 : normalExamineEntity.getWeight());
        examineReportVO.setSpecialExamineList(specialExamineVOS);
        return examineReportVO;
    }

    //填写基础体检报告
    public void addNormalExamine(Map<String, Object> param) {
        NormalExamineEntity normalExamineEntity = new NormalExamineEntity();
        String name = param.get("name").toString();
        String gender = examinerDao.selectByMap(MapUtil.of("name", name)).get(0).getGender();
        double height = Double.parseDouble(param.get("height").toString());
        double weight = Double.parseDouble(param.get("weight").toString());
        double bmi = calculateBMI(weight, height);
        if ("男".equals(gender)) {
            normalExamineEntity.setIdealWeight(calculateIdealWeightForMale(height));
        } else {
            normalExamineEntity.setIdealWeight(calculateIdealWeightForFemale(height));
        }
        normalExamineEntity.setBmi(bmi);
        normalExamineEntity.setHeight(height);
        normalExamineEntity.setWeight(weight);
        String systolicPressure = param.get("systolicPressure").toString();
        String diastolicPressure = param.get("diastolicPressure").toString();
        normalExamineEntity.setSystolicPressure(Integer.parseInt(systolicPressure));
        normalExamineEntity.setDiastolicPressure(Integer.parseInt(diastolicPressure));
        normalExamineEntity.setName(name);
        normalExamineDao.insert(normalExamineEntity);
    }

    //填写特殊体检报告
    public ResponseDto addSpecialExamine(Map<String, Object> param) {
        SpecialExamineEntity specialExamineEntity = new SpecialExamineEntity();
        String name = param.get("name").toString();
        long projectId = Long.parseLong(param.get("projectId").toString());
        ProjectEntity projectEntity = projectDao.selectById(projectId);
        if (projectEntity == null) {
            return ResponseDto.fail("项目不存在");
        }
        Double maxLevel = projectEntity.getMaxLevel();
        Double minLevel = projectEntity.getMinLevel();
        double result = Double.parseDouble(param.get("result").toString());
        String error = result < minLevel || result > maxLevel ? "异常" : "正常";
        specialExamineEntity.setName(name);
        specialExamineEntity.setProjectId(projectId);
        specialExamineEntity.setResult(result);
        specialExamineEntity.setError(error);
        specialExamineDao.insert(specialExamineEntity);
        return ResponseDto.success();
    }

    //主检医师填写建议审核
    public ResponseDto addSuggest(Map<String, Object> param) {
        String name = param.get("name").toString();
        long projectId = Long.parseLong(param.get("projectId").toString());
        ProjectEntity projectEntity = projectDao.selectById(projectId);
        if (projectEntity == null) {
            return ResponseDto.fail("项目不存在");
        }
        String suggest = param.get("suggest").toString();
        Wrapper<SpecialExamineEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("name", name).eq("projectId", projectId);
        SpecialExamineEntity specialExamineEntity = new SpecialExamineEntity();
        specialExamineEntity.setSuggest(suggest);
        specialExamineEntity.setName(name);
        specialExamineEntity.setProjectId(projectId);
        specialExamineDao.update(specialExamineEntity, wrapper);
        return ResponseDto.success();
    }

    /**
     * 计算BMI指数
     *
     * @param weight 体重，单位：千克
     * @param height 身高，单位：米
     * @return BMI指数
     */
    public static double calculateBMI(double weight, double height) {
        return weight / (height * height);
    }

    /**
     * 计算男性理想体重
     *
     * @param height 身高，单位：米
     * @return 男性理想体重，单位：千克
     */
    public static double calculateIdealWeightForMale(double height) {
        return (height - 1) * 100 - (height - 1) * 100 * 0.1;
    }

    /**
     * 计算女性理想体重
     *
     * @param height 身高，单位：米
     * @return 女性理想体重，单位：千克
     */
    public static double calculateIdealWeightForFemale(double height) {
        return (height - 1) * 100 - (height - 1) * 100 * 0.15;
    }
}
